<?php
namespace Hawk\Controller;
use \Hawk\Controller\IndexController;
class CustomerController extends IndexController 
{
	/**
     * 添加客户
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
	public function add(){
		if(IS_PSOT && !empty($_POST)){
			$model = D('Hawk/Customer');
			// hecho($_POST);die;
    		if($model->create(I('post.'), 1))
    		{
    			if($id = $model->add())
    			{
    				//写入操作日志
                    $content = "成功添加客户".$_POST['cusname'];
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
                    if(I('post.src')=='customer'){
                    	$this->success('添加成功！', U('lst?p='.I('get.p')));
                    	exit;
                    }
    				$this->success('添加成功！', U('Sale/lst?p='.I('get.p')));
    				exit;
    			}else{
    				$content = "添加客户".$_POST['cusname']."失败";
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
    			}
    		}
    		$this->error($model->getError());
		}
		//客户类型
		$tmodel = M('CustomerType');
		$type = $tmodel->select();
		$this->assign('type',$type);
		//资源类型
		$rmodel = M('ResourceType');
		$rtype = $rmodel->select();
		$this->assign('rtype',$rtype);
		if(!empty(I('get.type'))){
			$this->assign('src',I('get.type'));
		}
		//销售主任/经理
		$amodel=D('Hawk/Admin');
		$sale['head'] = $amodel->getRoleToAdmin('销售主任');
		$sale['manage'] = $amodel->getRoleToAdmin('销售经理');
		$this->assign('sale',$sale);
		$this->display();
	}
	/**
     * 编辑客户
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
	public function edit(){
		$id = I('get.id');
        $model = D('Hawk/Customer');
        if(IS_POST && !empty($_POST))
        {
        	// hecho($_POST);die;
            if($model->create(I('post.'),5))
            {
                if($model->save() !== FALSE)
                {
                	//写入操作日志
	                $content = "成功修改客户-ID=".$id;
	                hawk_operation_log(session('id'),hawk_get_ip(),$content);
                	if(!empty($_POST['src'])){
                		$this->success('修改成功！', U($_POST['src'],array('id'=>$_POST['id'])));
                		exit;
                	}
                    $this->success('修改成功！', U('lst', array('p' => I('get.p', 1))));
                    exit;
                }else{
                	$content = "失败修改客户-ID=".$id;
	                hawk_operation_log(session('id'),hawk_get_ip(),$content);
                }
            }
            $this->error($model->getError());
        }
        //客户信息
        $amodel=D('Hawk/Admin');
        $cusinfo=$model->find($id);
        $pmodel = M('Part');
        $part_self = $pmodel->find($cusinfo['part']);
        $cusinfo['part_name']=$part_self['name'];
        $admin_self = $amodel->find($cusinfo['sale_worker']);
        $cusinfo['sale_worker_name'] =$admin_self['nickname'];        
        $this->assign('cusinfo',$cusinfo);
        //销售主任/经理
        
		$sale['head'] = $amodel->getRoleToAdmin('销售主任');
		$sale['manager'] = $amodel->getRoleToAdmin('销售经理');
		$this->assign('sale',$sale);
		//商务经理
		$business['manager']= $amodel->getRoleToAdmin('商务经理');
		$this->assign('business',$business);

		//商务部员工
		$bu_self = $pmodel->where('name="商务部"')->find();
		$bu_part = $amodel->getChildren($pmodel,$bu_self['id']);
		array_unshift($bu_part, $bu_self['id']);
        //查询目标员工
		$aamodel =M('Admin');
		$bu_staff = $aamodel->field('id,nickname')->where(array('part_id'=>array('IN',$bu_part)))->select();
		$this->assign('bu_staff',$bu_staff);

        //客户类型
        $tmodel = M('CustomerType');
		$type = $tmodel->select();
		$this->assign('type',$type);
		//资源类型
		$rmodel = M('ResourceType');
		$rtype = $rmodel->select();
		$this->assign('rtype',$rtype);
		//部门
		$part = $pmodel->select();
		$this->assign('part',$part);
		//查询员工

		$part_self = $pmodel->where('name="销售部"')->find();
        //查询子部门
		$part = $amodel->getChildren($pmodel,$part_self['id']);
		array_unshift($part, $part_self['id']);
        //查询目标员工
		$staff = $aamodel->field('id,nickname')->where(array('part_id'=>array('IN',$part)))->select();
		$this->assign('staff',$staff);
        $this->display();
	}
	/**
     * 还原客户
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function restore()
    {
        $model = M('Customer');
        $model->where(array(
            'id' => array('eq', I('get.id')),
        ))->setField('is_delete', 1);
        $this->success('操作成功！', U('recyclelst', array('p' => I('get.p', 1))));
    }
    /**
     * 放入回收站
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function recycle()
    {
        $model = M('Customer');
        $model->where(array(
            'id' => array('eq', I('get.id')),
        ))->setField('is_delete', 0);
        $this->success('操作成功！', U('lst', array('p' => I('get.p', 1))));
    }
    /**
     * 删除客户
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
	public function delete(){
		$model = D('Hawk/Customer');
		if($model->delete(I('get.id', 0)) !== FALSE)
    	{
    		$content = "成功删除客户-ID=".I('get.id');
	        hawk_operation_log(session('id'),hawk_get_ip(),$content);
    		$this->success('删除成功！', U('lst', array('p' => I('get.p', 1))));
    		exit;
    	}else{
    		$content = "失败删除客户-ID=".I('get.id');
	        hawk_operation_log(session('id'),hawk_get_ip(),$content);
    		$this->error($model->getError());
    	}
	}
	/**
     * 审核客户
     * @author hawk <2271030162@qq.com>
     * @return json
     */
	public function check(){
		if (IS_POST&&!empty($_POST)) {
			$model=M('Customer');
			if($_POST['type']==1){
				//审核通过
				if($_POST['is_checked']==0){
					$data['is_checked']=6;
					$re = $model->where(array('id'=>array('eq',$_POST['cus_id'])))->save($data);
					if($re>0){
						$content = "客户-ID=".$_POST['cus_id']."-一审通过";
	        			hawk_operation_log(session('id'),hawk_get_ip(),$content);
						echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
					}else{						
						echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
					}
				}elseif ($_POST['is_checked']==1) {
					$data['is_checked']=7;
					$re = $model->where(array('id'=>array('eq',$_POST['cus_id'])))->save($data);
					if($re>0){	
						$content = "客户-ID=".$_POST['cus_id']."-二审通过";
	        			hawk_operation_log(session('id'),hawk_get_ip(),$content);					
						echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
					}else{
						
						echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
					}
				}else{
					echo json_encode(array('code'=>1000,'msg'=>'无此权限！'));
				}	
			}elseif($_POST['type']==0){
				//审核不通过
				if($_POST['is_checked']==0){
					$data['is_checked']=1;
					$re = $model->where(array('id'=>array('eq',$_POST['cus_id'])))->save($data);
					if($re>0){
						$content = "客户-ID=".$_POST['cus_id']."-一审未通过";
	        			hawk_operation_log(session('id'),hawk_get_ip(),$content);
						echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
					}else{
						echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
					}
				}elseif ($_POST['is_checked']==1) {
					$data['is_checked']=2;
					$re = $model->where(array('id'=>array('eq',$_POST['cus_id'])))->save($data);
					if($re>0){
						$content = "客户-ID=".$_POST['cus_id']."-二审未通过";
	        			hawk_operation_log(session('id'),hawk_get_ip(),$content);
						echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
					}else{
						echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
					}
				}else{
					echo json_encode(array('code'=>1000,'msg'=>'无此权限！'));
				}
			}else{
				echo json_encode(array('code'=>1000,'msg'=>'无此权限！'));
			}			
		}else{
			echo json_encode(array('code'=>1000,'msg'=>'无此权限！'));
		}
	}
	/**
     * ajax修改消费金额
     * @author hawk <2271030162@qq.com>
     * @return json
     */
	public function consume(){
		if(IS_POST){
			$model = M('Customer');
			$data['consume']=$_POST['consume'];
			$data['updatetime']=time();
			$re = $model->where(array('id'=>array('eq',$_POST['id'])))->save($data);
			//echo $model->getLastSql();die;
			if($re!==false){
				$content = "修改消费金额为".$_POST['consume'];
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
				echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
			}else{
				$content = "失败修改消费金额为".$_POST['consume'];
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
				echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
			}
		}
	}
	/**
     * 商务添加客户资金操作
     * @author hawk <2271030162@qq.com>
     * @return mix
     */	
	public function moneyadd(){
		if(IS_POST){			
			$data=$_POST['data'];
			$data['addtime']=time();
			$data['updatetime']=time();
			$model =M('');
			//开启事务
			$model->startTrans();
			//资金操作主表添加
			$id = $model->table(C('DB_PREFIX').'money_log')->data($data)->add();
			if($id===false){
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}
			$data['log_id']=$id;
			//添加专员分成情况
			for ($i=0; $i <count($_POST['sale_worker']['worker']) ; $i++) { 
				$data['sale_worker']=$_POST['sale_worker']['worker'][$i];
				$data['percent']=$_POST['percent']['worker'][$i];
				$data['sale_type']='worker';
				//资金操作业务分成添加
				$re = $model->table(C('DB_PREFIX').'money_divide')->data($data)->add();
				if($re===false){
					//若有一次不成功事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}				
			}
			//添加主任分成情况
			for ($i=0; $i <count($_POST['sale_worker']['head']) ; $i++) { 
				$data['sale_worker']=$_POST['sale_worker']['head'][$i];
				$data['percent']=$_POST['percent']['head'][$i];
				$data['sale_type']='head';
				//资金操作业务分成添加
				$re = $model->table(C('DB_PREFIX').'money_divide')->data($data)->add();
				if($re===false){
					//若有一次不成功事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}				
			}
			//添加主任分成情况
			for ($i=0; $i <count($_POST['sale_worker']['manager']) ; $i++) { 
				$data['sale_worker']=$_POST['sale_worker']['manager'][$i];
				$data['percent']=$_POST['percent']['manager'][$i];
				$data['sale_type']='manager';
				//资金操作业务分成添加
				$re = $model->table(C('DB_PREFIX').'money_divide')->data($data)->add();
				if($re===false){
					//若有一次不成功事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}				
			}
			//更新客户表的updatetime
			$this_cus = $model->table(C('DB_PREFIX').'money_log')->find($id);
			$up_re = $model
			->table(C('DB_PREFIX').'customer')
			->where(array(
				'id'=>array('eq',$this_cus['cus_id'])
				))
			->save(array('updatetime'=>time()));
			if($up_re ===false){
				$content = "删除客户资金操作(".$_POST['id'].")时，更新客户(".$this_cus['cus_id'].")时间失败";
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
	        	$model->rollback();
				echo json_encode(array('code'=>1,'msg'=>'操作失败,请联系技术部！'));
			}
			//都成功事务提交
			$model->commit();
			//操作写入日志
			$content = "添加客户".$data['cus_id']."资金操作".$data['typeid'].$data['OpFare']."出入金日志ID-".$data['log_id'];
	        hawk_operation_log(session('id'),hawk_get_ip(),$content);
			echo json_encode(array('code'=>1,'msg'=>'操作成功！'));								
		}
		if(!empty(I('get.id'))){
			$model = M('MoneyType');
			$pmodel = M('Part');
			$amodel =D('Hawk/Admin');
			$moneyType = $model->select();
			$this->assign('mtype',$moneyType);
			$this->assign('cid',I('get.id'));
			$data['worker'] = $amodel->getRoleToAdmin('销售专员');
			$data['head'] = $amodel->getRoleToAdmin('销售主任');
			$data['manager'] = $amodel->getRoleToAdmin('销售经理');
			$this->assign('data',$data);
			$this->display();
		}
	}
	/**
     * 商务修改客户资金操作
     * @author hawk <2271030162@qq.com>
     * @return mix
     */	
	public function moneyedit(){
		if(IS_POST){
			$data=$_POST['data'];
			$data['addtime']=time();
			$data['updatetime']=time();
			$model =M('');
			//开启事务
			$model->startTrans();
			//资金操作主表添加
			$re = $model->table(C('DB_PREFIX').'money_log')
						->where(array(
							'id'=>array('eq',$_POST['log_id'])
							))
						->data($data)
						->save();
			if($id===false){
					//事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}
			//资金操作业务分成删除
			$de_re = $model->table(C('DB_PREFIX').'money_divide')
				  ->where(array(
				  	'log_id'=>array('eq',$_POST['log_id'])
				  	))
				  ->delete();
			if($de_re===false){
					//事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}
			$data['log_id']=$_POST['log_id'];

			//添加专员分成情况
			for ($i=0; $i <count($_POST['sale_worker']['worker']) ; $i++) { 
				$data['sale_worker']=$_POST['sale_worker']['worker'][$i];
				$data['percent']=$_POST['percent']['worker'][$i];
				$data['sale_type']='worker';
				//资金操作业务分成添加
				$re = $model->table(C('DB_PREFIX').'money_divide')->data($data)->add();
				if($re===false){
					//若有一次不成功事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}				
			}
			//添加主任分成情况
			for ($i=0; $i <count($_POST['sale_worker']['head']) ; $i++) { 
				$data['sale_worker']=$_POST['sale_worker']['head'][$i];
				$data['percent']=$_POST['percent']['head'][$i];
				$data['sale_type']='head';
				//资金操作业务分成添加
				$re = $model->table(C('DB_PREFIX').'money_divide')->data($data)->add();
				if($re===false){
					//若有一次不成功事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}				
			}
			//添加经理分成情况
			for ($i=0; $i <count($_POST['sale_worker']['manager']) ; $i++) { 
				$data['sale_worker']=$_POST['sale_worker']['manager'][$i];
				$data['percent']=$_POST['percent']['manager'][$i];
				$data['sale_type']='manager';
				//资金操作业务分成添加
				$re = $model->table(C('DB_PREFIX').'money_divide')->data($data)->add();
				if($re===false){
					//若有一次不成功事务回滚
					$model->rollback();
					echo json_encode(array('code'=>0,'msg'=>'操作失败,请联系网站管理员！'));
				}				
			}
			//更新客户表的updatetime
			$this_cus = $model->table(C('DB_PREFIX').'money_log')->find($_POST['log_id']);
			// hecho($this_cus);die;
			$up_re = $model
			->table(C('DB_PREFIX').'customer')
			->where(array(
				'id'=>array('eq',$this_cus['cus_id'])
				))
			->save(array('updatetime'=>time()));
			if($up_re ===false){
				$content = "删除客户资金操作(".$_POST['id'].")时，更新客户(".$this_cus['cus_id'].")时间失败";
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
	        	$model->rollback();
				echo json_encode(array('code'=>1,'msg'=>'操作失败,请联系技术部！'));
			}
			//都成功事务提交
			$model->commit();
			//操作写入日志
			$content = "修改客户(".$data['cus_id'].")资金操作".$data['typeid'].$data['OpFare']."出入金日志ID-".$data['log_id'];
	        hawk_operation_log(session('id'),hawk_get_ip(),$content);
			echo json_encode(array('code'=>1,'msg'=>'操作成功！'));	
		}
		if(!empty(I('get.id'))){
			$model = M('');
			$mtmodel = M('MoneyType');
			$pmodel = M('Part');
			$amodel =D('Hawk/Admin');
			$moneyType = $mtmodel->select();
			$this->assign('mtype',$moneyType);
			$this->assign('cid',I('get.id'));
			//查询该次详情
			$data['money_log'] = $model->table(C('DB_PREFIX').'money_log')->find(I('get.id'));
			//该操作分成详情

			//专员
			$data['worker_money_divide'] = $this->_divide_info(array(
										  	'log_id'=>array('eq',$data['money_log']['id']),
										  	'sale_type'=>array('eq','worker')
										  	));
			//主任
			$data['head_money_divide'] = $this->_divide_info(array(
										  	'log_id'=>array('eq',$data['money_log']['id']),
										  	'sale_type'=>array('eq','head')
										  	));
			//经理
			$data['manager_money_divide'] = $this->_divide_info(array(
										  	'log_id'=>array('eq',$data['money_log']['id']),
										  	'sale_type'=>array('eq','manager')
										  	));
			$data['worker'] = $amodel->getRoleToAdmin('销售专员');
			$data['head'] = $amodel->getRoleToAdmin('销售主任');
			$data['manager'] = $amodel->getRoleToAdmin('销售经理');
			$this->assign('data',$data);
			$this->display();
		}
	}
	/**
     * 商务删除客户资金操作
     * @author hawk <2271030162@qq.com>
     * @return mix
     */	
	public function moneydelete(){
		if(!empty($_POST)){
			$model = M('');
			//开启事务
			$model->startTrans();
			//删除分成表数据
			$re1 = $model->table(C('DB_PREFIX').'money_divide')->where(array('log_id'=>array('eq',$_POST['id'])))->delete();
			if($re1===false){
				$content = "删除客户资金操作(".$_POST['id'].")失败";
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
	        	$model->rollback();
				echo json_encode(array('code'=>1,'msg'=>'操作失败,请联系技术部！'));
			}
			//添加更新客户资料时间
			$this_cus = $model->table(C('DB_PREFIX').'money_log')->find($_POST['id']);
			$up_re = $model
			->table(C('DB_PREFIX').'customer')
			->where(array(
				'id'=>array('eq',$this_cus['cus_id'])
				))
			->save(array('updatetime'=>time()));
			if($up_re ===false){
				$content = "删除客户资金操作(".$_POST['id'].")时，更新客户(".$this_cus['cus_id'].")时间失败";
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
	        	$model->rollback();
				echo json_encode(array('code'=>1,'msg'=>'操作失败,请联系技术部！'));
			}
			$re = $model->table(C('DB_PREFIX').'money_log')->where(array('id'=>array('eq',$_POST['id'])))->delete();
			if($re){
				$content = "删除客户资金操作(".$_POST['id'].")";
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
	        	$model->commit();
				echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
			}else{
				$content = "删除客户资金操作(".$_POST['id'].")失败";
	        	hawk_operation_log(session('id'),hawk_get_ip(),$content);
	        	$model->rollback();
				echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
			}
		}else{
			echo json_encode(array('code'=>1000,'msg'=>'无此权限！'));
		}
	}
	/**
     * 资金操作详情
     * @author hawk <2271030162@qq.com>
     * @return mix
     */	
	public function moneyinfo(){
		if(!empty(I('get.id'))){
			$model=M('');
			//销售专员
			$divide_worker_list = $this->_is_divide(I('get.id'),'worker');
			$divide_list['divide_worker_list']=$this->_divide_info_process($divide_worker_list);
			//销售主任
			$divide_head_list = $this->_is_divide(I('get.id'),'head');
			$divide_list['divide_head_list']=$this->_divide_info_process($divide_head_list);
			//销售经理
			$divide_manager_list = $this->_is_divide(I('get.id'),'manager');
			$divide_list['divide_manager_list']=$this->_divide_info_process($divide_manager_list);	
			$this->assign('data',$divide_list);
			$this->display();
		}else{
			hecho('无此权限！');
		}		
	}
	/**
     * 资金操作详情数据处理
     * @author hawk <2271030162@qq.com>
     * @param  $data array
     * @return array
     */	
	private function _divide_info_process($data){
		$model=M('');
		$mlmodel = D('Hawk/Admin');
		foreach ($data as $k => $v) {
			$cus = $model->table(C('DB_PREFIX').'customer')->find($v['cus_id']);
			$data[$k]['cus_name']=$cus['cusname'];
			$data[$k]['sale_worker_name']=$mlmodel->getAdminName($v['sale_worker']);
		}
		return $data;
	}
	/**
     * 客户详情
     * @author hawk <2271030162@qq.com>
     * @return mix
     */	
	public function moreinfo(){
		$cmodel = M('Customer');
		$cusinfo = $cmodel->find(I('get.id'));
		$pmodel = M('Part');
        $part_self = $pmodel->find($cusinfo['part']);
        $cusinfo['part_name']=$part_self['name'];
        $amodel = M('Admin');
        $admin_self = $amodel->find($cusinfo['sale_worker']);
        $cusinfo['sale_worker'] =$admin_self['nickname'];
        //替换ID to name
        $mlmodel = D('Hawk/Admin'); 
        $cusinfo['sale_head_name']=$mlmodel->getAdminName($cusinfo['sale_head']);
        $cusinfo['sale_manager_name']=$mlmodel->getAdminName($cusinfo['sale_manager']);
        $cusinfo['business_manager_name']=$mlmodel->getAdminName($cusinfo['business_manager']);
        $cusinfo['businesser_name']=$mlmodel->getAdminName($cusinfo['businesser']);
		$mmodel = M('MoneyLog');

		$where = array(
					'cus_id'=>array('eq',I('get.id')),
				);
		$count = $mmodel->where($where)->count();
		$page = new \Think\Page($count, 5);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$cusinfo['page'] = $page->show();

		$moneyLog = $mmodel->where($where)
				->order('addtime desc')
				->limit($page->firstRow.','.$page->listRows)
				->select();
		foreach ($moneyLog as $k => $v) {
			$cinfo = $cmodel->find($v['cus_id']);
			$moneyLog[$k]['cusname']=$cinfo['cusname'];	
			$moneyLog[$k]['addtime']=date('Y-m-d H:i:s',$v['addtime']);
			//业务员分成情况
			$moneyLog[$k]['divide_sale_worker'] = $this->_divide_sale($this->_is_divide($v['id'],'worker'));
			//主任分成情况
			$moneyLog[$k]['divide_sale_head'] = $this->_divide_sale($this->_is_divide($v['id'],'head'));
			//经理分成情况
			$moneyLog[$k]['divide_sale_manager'] = $this->_divide_sale($this->_is_divide($v['id'],'manager'));
			//归属部门
			$moneyLog[$k]['part_name'] = $this->_divide_sale();
		}
		//资源类型
		$rmodel = M('ResourceType');
		$cusinfo['rtype'] = $rmodel->select();
		//客户类型
        $tmodel = M('CustomerType');
		$type = $tmodel->select();
		$this->assign('type',$type);
		$cusinfo['moneyLog']=$moneyLog;
		$this->assign('cusinfo',$cusinfo);
		$this->display();
	}
	/**
     * 客户列表
     * @author hawk <2271030162@qq.com>
     * @return mix
     */	
	public function lst(){
		$model = M('');
		$mlmodel = D('Hawk/Customer');
		if(IS_POST){
			if(!empty($_POST['part_id'])){
				$pid = $_POST['part_id'];
				$search['part_id'] = $_POST['part_id'];
			}else{
				$pid = '';
			}
			if(!empty($_POST['sale_worker'])){
				$sale_worker = $_POST['sale_worker'];
				$search['sale_worker'] = $_POST['sale_worker'];
			}else{
				$sale_worker = '';
			}
			if(!empty($_POST['cus_id'])){
				$customer = $_POST['cus_id'];
				$search['cus_id'] = $_POST['cus_id'];
			}else{
				$customer = '';
			}
			if(!empty($_POST['time_start'])){
				$time_start =$_POST['time_start'];
				$search['time_start']=$_POST['time_start'];
			}else{
				$time_start ='';
			}
			if(!empty($_POST['time_end'])){
				$time_end =$_POST['time_end'];
				$search['time_end']=$_POST['time_end'];
			}else{
				$time_end = '';
			}
		}
		if(!empty($pid)){
			$part_id = $this->_part_id($pid);
			$sale_admin = $model
			->table(C('DB_PREFIX').'admin')
			->field('id,nickname')
			->where(array('part_id'=>array('IN',$part_id)))
			->select();
			foreach ($sale_admin as $k => $v) {
				$sale_admin_id[$k]=$v['id'];
			}
			if(!empty($sale_admin_id)){
				$where['sale_worker']=array('IN',$sale_admin_id);
			}else{
				$where['sale_worker']=array('eq',0);
			}		
		}
		if(!empty($sale_worker)){
			$where['sale_worker']=$sale_worker;
		}
		if(!empty($customer)){
			$where['id']= $customer;
		}
		if(!empty($time_start)&&!empty($time_end)){
			$where['addtime']=array(array('gt',strtotime($time_start)),array('lt',strtotime($time_end)+3600*24)); 
		}else if(!empty($time_start)&&empty($time_end)){
			$where['addtime']=array('gt',strtotime($time_start));
		}else if(empty($time_start)&&!empty($time_end)){
			$where['addtime']=array('lt',strtotime($time_end)+3600*24);
		}
		// hecho($where);die;
		$count = $model->table(C('DB_PREFIX').'customer')->where($where)->count();
		$page = new \Think\Page($count, 10);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$list['page'] = $page->show();
		$list['list'] = $model
		->table(C('DB_PREFIX').'customer')
		->where($where)
		->limit($page->firstRow . ',' . $page->listRows)
		->select();
		foreach ($list['list'] as $k => $v) {
			$list['list'][$k]['allMoney'] = array_sum($mlmodel->getCustomerMoney($v['id']));
		}
		//查询部门
		$list['part'] =$model->table(C('DB_PREFIX').'part')->select();
		//查询涉及业务员		
		$list['sale_worker'] = $model->table(C('DB_PREFIX').'admin')->order('id desc')->select();
		//查询涉及客户
		$list['customer'] = $model->table(C('DB_PREFIX').'customer')->select();
		$list['search']=$search;
		$this->assign('list',$list);
		$tmodel = M('CustomerType');
		$type = $tmodel->select();
		$this->assign('type',$type);
	    $this->display(); 
	}
	/**
     * 部门层级筛选(返回部门ID)
     * @author hawk <2271030162@qq.com>
     * @param  $pid int
     * @return array
     */	
	private function _part_id($pid){
		$amodel = D('Hawk/Admin');
		$pmodel=M('Part');
		//通过部门层级查询
		if(empty($pid)){
			$pid = session('staff_info')['part_id'];
		}
		$part_id = $amodel->getChildren($pmodel,$pid);
		array_unshift($part_id, $pid);
		return $part_id;
	}
	/**
     * part_id 涉及业务员ID
     * @author hawk <2271030162@qq.com>
     * @param  $pid int
     * @return array
     */
	private function _part_admin($part_id){
		$model = M('');
		$array_part_id = $this->_part_id($part_id);
		$admin_id = $model
		->table(C('DB_PREFIX').'admin')
		->where(array('part_id'=>array('in',$array_part_id)))
		->select();
		foreach ($admin_id as $k=> $v){
			$admin[]=$v['id']; 
		}
		return $admin;
	}
	/**
     * 该客户，该次出入金操作分成情况
     * @author hawk <2271030162@qq.com>
     * @param  $money_log_id int
     * @param  $sale_type string
     * @return array
     */
	private function _is_divide($money_log_id,$sale_type){
		$model= M('');
		$divide_data = $model
		->table(C('DB_PREFIX').'money_divide')
		->where(array(
			'log_id'=>array('eq',$money_log_id),
			'sale_type'=>array('eq',$sale_type)
			))
		->select();
		return $divide_data;
	}
	/**
     * 查询当次操作分成详情
     * @author hawk <2271030162@qq.com>
     * @param  $where array 查询条件
     * @return array
     */
	private function _divide_info($where=true){
		$model = M('');
		$data = $model
		->table(C('DB_PREFIX').'money_divide')
		->where($where)
		->select();
		return $data;
	}
	/**
     * 分成详情添加
     * @author hawk <2271030162@qq.com>
     * @param  $data 基础数据 array()
     * @param  $divide_info 各级分成数据 array()
     * @param  
     * @return mix
     */
	private function _divide_add($data,$divide_info,$type){
		
	}
	/**
     * 每次出入金操作分成者
     * @author hawk <2271030162@qq.com>
     * @param  $divide_data array
     * @return string
     */
	private function _divide_sale($divide_data){
		$model = D('Hawk/Admin');
		if(is_array($divide_data)){
			foreach ($divide_data as $k => $v) {
				$nickname = $model->getAdminName($v['sale_worker']);
				if(!empty($nickname)){
					$divide_sale .=$nickname.'('.$v['percent'].')/' ;
				}
			}
		}else{
			$divide_sale = '';
		}
		return $divide_sale;
	}
	/**
     * 每次出入金操作分成者
     * @author hawk <2271030162@qq.com>
     * @param  $divide_data array
     * @return string
     */
	private function _divide_part($divide_data){
		if(is_array($divide_data)){
			$model= M('');
			$pmodel = D('Hawk/Part');
			foreach ($divide_data as $k => $v) {
				$admin_info = $model
				->table(C('DB_PREFIX').'admin')
				->find($v['sale_worker']);
				$divide_part .= substr($pmodel->getPartName($admin_info['part_id']),6).'/';
			}
		}
		return $divide_part;
	}
	/**
     * 财务所需列表
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
	public function finance(){
		$model=M('');
		$amodel = D('Hawk/Admin');
		$where=array();
		if(IS_POST){	
			if(!empty($_POST['part_id'])){
				$pid = $_POST['part_id'];
				$search['part_id'] = $_POST['part_id'];
			}else{
				$pid = session('staff_info')['part_id'];
			}
			if(!empty($_POST['sale_worker'])){
				$sale_worker = $_POST['sale_worker'];
				$search['sale_worker'] = $_POST['sale_worker'];
			}else{
				$sale_worker = '';
			}
			if(!empty($_POST['cus_id'])){
				$customer = $_POST['cus_id'];
				$search['cus_id'] = $_POST['cus_id'];
			}else{
				$customer = '';
			}
			if(!empty($_POST['time_start'])){
				$time_start =$_POST['time_start'];
				$search['time_start']=$_POST['time_start'];
			}else{
				$time_start ='';
			}
			if(!empty($_POST['time_end'])){
				$time_end =$_POST['time_end'];
				$search['time_end']=$_POST['time_end'];
			}else{
				$time_end = '';
			}
		}
		if(!empty($pid)){
			$admin=$this->_part_admin($pid);
			if(!empty($admin)){
				$where1['sale_worker']=array('in',$admin);
				if(!empty($sale_worker)){
					$where1['sale_worker']=$sale_worker;
				}
				$money_log = $model->table(C('DB_PREFIX').'money_divide')->where($where1)->group('log_id')->select();
				foreach ($money_log as $k => $v) {
					$log_id[] =$v['log_id']; 
				}
				if(!empty($log_id)){
					$where['ml.id']=array('in',$log_id);
				}else{
					$where['ml.id']=false;
				}
				
			}
		}
		if(!empty($customer)){
			$where['cus_id']=$customer;
		}
		if(!empty($time_start)&&!empty($time_end)){
			$where['operate_time']=array(array('gt',$time_start),array('lt',date('Y-m-d',strtotime($time_end)+3600*24))); 
		}else if(!empty($time_start)&&empty($time_end)){
			$where['operate_time']=array('gt',strtotime($time_start));
		}else if(empty($time_start)&&!empty($time_end)){
			$where['operate_time']=array('lt',date('Y-m-d',strtotime($time_end)+3600*24));
		}
		$count = $model
		->table(C('DB_PREFIX').'money_log')
		->alias('ml')
		->where($where)
		->join('left join hawk_customer c on ml.cus_id=c.id')
		->count();
		$page = new \Think\Page($count, 10);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$page->setConfig('first', '首页');
		$page->setConfig('last', '尾页');
		$cusinfo['page'] = $page->show();
		$moneyLog = $model
		->table(C('DB_PREFIX').'money_log')
		->field('ml.*,c.server_time_start,c.server_time_end,c.cusname')
		->alias('ml')
		->where($where)
		->join('left join hawk_customer c on ml.cus_id=c.id')
		->order('addtime desc')
		->limit($page->firstRow.','.$page->listRows)
		->select();
		foreach ($moneyLog as $k => $v) {
			//业务员分成情况
			$moneyLog[$k]['divide_sale_worker'] = $this->_divide_sale($this->_is_divide($v['id'],'worker'));
			//主任分成情况
			$moneyLog[$k]['divide_sale_head'] = $this->_divide_sale($this->_is_divide($v['id'],'head'));
			//经理分成情况
			$moneyLog[$k]['divide_sale_manager'] = $this->_divide_sale($this->_is_divide($v['id'],'manager'));
			//部门
			$moneyLog[$k]['divide_part']= $this->_divide_part($this->_is_divide($v['id'],'head'));
		}
		$cusinfo['moneyLog']=$moneyLog;
		$this->assign('cusinfo',$cusinfo);
		//部门
		$search['info']['part']=$model
		->table(C('DB_PREFIX').'part')
		->where('is_use=1')
		->order('sort desc')
		->select();
		//业务员
		$search['info']['sale_worker'] = $amodel->getRoleToAdmin('销售专员');
		//客户
		$search['info']['customer'] = $model
		->table(C('DB_PREFIX').'customer')
		->select();
		$this->assign('search',$search);
		$this->display();
	}
	/**
     * 财务列表导出
     * @author hawk <2271030162@qq.com>
     * @param  $divide_data array
     * @return mix
     */
	public function exportdata(){
		$model=M('');
		$amodel = D('Hawk/Admin');
		$where=array();
		if(IS_POST){	
			if(!empty($_POST['part_id'])){
				$pid = $_POST['part_id'];
			}else{
				$pid = session('staff_info')['part_id'];
			}
			if(!empty($_POST['sale_worker'])){
				$sale_worker = $_POST['sale_worker'];
			}else{
				$sale_worker = '';
			}
			if(!empty($_POST['cus_id'])){
				$customer = $_POST['cus_id'];
			}else{
				$customer = '';
			}
			if(!empty($_POST['time_start'])){
				$time_start =$_POST['time_start'];
			}else{
				$time_start ='';
			}
			if(!empty($_POST['time_end'])){
				$time_end =$_POST['time_end'];
			}else{
				$time_end = '';
			}
		}
		if(!empty($pid)){
			$admin=$this->_part_admin($pid);
			if(!empty($admin)){
				$where1['sale_worker']=array('in',$admin);
				if(!empty($sale_worker)){
					$where1['sale_worker']=$sale_worker;
				}
				$money_log = $model->table(C('DB_PREFIX').'money_divide')->where($where1)->group('log_id')->select();
				foreach ($money_log as $k => $v) {
					$log_id[] =$v['log_id']; 
				}
				if(!empty($log_id)){
					$where['ml.id']=array('in',$log_id);
				}else{
					$where['ml.id']=false;
				}
				
			}
		}
		if(!empty($customer)){
			$where['cus_id']=$customer;
		}
		if(!empty($time_start)&&!empty($time_end)){
			$where['operate_time']=array(array('gt',$time_start),array('lt',date('Y-m-d',strtotime($time_end)+3600*24))); 
		}else if(!empty($time_start)&&empty($time_end)){
			$where['operate_time']=array('gt',strtotime($time_start));
		}else if(empty($time_start)&&!empty($time_end)){
			$where['operate_time']=array('lt',date('Y-m-d',strtotime($time_end)+3600*24));
		}
		$moneyLog = $model
		->table(C('DB_PREFIX').'money_log')
		->field('ml.*,c.server_time_start,c.server_time_end,c.cusname')
		->alias('ml')
		->where($where)
		->join('left join hawk_customer c on ml.cus_id=c.id')
		->order('addtime desc')
		->limit($page->firstRow.','.$page->listRows)
		->select();
		foreach ($moneyLog as $k => $v){
			//日期
			$data[$k][]=$v['operate_time'];
			//客户名称
			$data[$k][] = $v['cusname'];
			//充值账号
			$data[$k][] = $v['number'];
			//部门
			$data[$k][]= $this->_divide_part($this->_is_divide($v['id'],'head'));
			//业务员分成情况
			$data[$k][] = $this->_divide_sale($this->_is_divide($v['id'],'worker'));
			//主任分成情况
			$data[$k][] = $this->_divide_sale($this->_is_divide($v['id'],'head'));
			//经理分成情况
			$data[$k][] = $this->_divide_sale($this->_is_divide($v['id'],'manager'));
			//服务期
			$data[$k][] = $v['server_time_start'];
			$data[$k][] = $v['server_time_end'];
			//充值金额
			$data[$k][] = $v['opfare'];
			//充值类型
			$data[$k][] = $v['typeid'];
		}
		// $title=array('operate_time','cusname','number','divide_part','divide_sale_worker','divide_sale_head','divide_sale_manager','server_time_start','server_time_end','OpFare','typeid');
		$title=array('日期','客户姓名','充值账号','部门','业务员','主任','经理','服务期-开始','服务期-结束','充值金额','充值类型');
		array_unshift($data,$title);
		echo json_encode($data);
	}
	public function export(){
		$data=$_GET['data'];
		$data=json_decode($data);
		hawk_create_xlsx($data,'客户充值记录.xlsx');
	}
}